package com.itheima.hotel.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.hotel.mapper.HotelMapper;
import com.itheima.hotel.pojo.Hotel;
import com.itheima.hotel.pojo.HotelDoc;
import com.itheima.hotel.pojo.PageResult;
import com.itheima.hotel.pojo.RequestParams;
import com.itheima.hotel.service.IHotelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tdunning.math.stats.Sort;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public PageResult search(RequestParams params) throws IOException {
        //1. 创建request
        SearchRequest request = new SearchRequest("hotel");
        //2.准备DSL
        //2-1 query
        buildBasicQuery(params,request);
        // 2-2 分页
        Integer page = params.getPage();
        Integer size = params.getSize();
        request.source().from((page - 1) * size).size(size);
        //2-3 高亮
        request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));
        // 2-4 周边酒店(推荐)
        String location = params.getLocation();
        if(StrUtil.isNotEmpty(location)){
            request.source().sort(
                    SortBuilders.geoDistanceSort("lcoation",new GeoPoint(location))
                    .order(SortOrder.ASC)
                    .unit(DistanceUnit.KILOMETERS)
            );
        }
        //3. 发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        //4.解析响应
        return handleResponse(response);
    }

    private void buildBasicQuery(RequestParams params, SearchRequest request) {
        //构建BooleanQuery
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //关键字
        String key = params.getKey();
        if(key == null || "".equals(key)){
            boolQuery.must(QueryBuilders.matchAllQuery());
        }else {
            boolQuery.must(QueryBuilders.matchQuery("all",key));
        }
        // 城市
        if(StrUtil.isNotEmpty(params.getCity())){
            boolQuery.filter(QueryBuilders.termQuery("city",params.getCity()));
        }
        //品牌
        if(StrUtil.isNotEmpty(params.getBrand())){
            boolQuery.filter(QueryBuilders.termQuery("brand",params.getBrand()));
        }
        // 星级
        if(StrUtil.isNotEmpty(params.getStarName())){
            boolQuery.filter(QueryBuilders.termQuery("startName",params.getStarName()));
        }
        // 价格
        if(params.getMinPrice() != null && params.getMaxPrice() != null){
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(params.getMinPrice()).lte(params.getMaxPrice()));
        }
        //2.算分控制
        QueryBuilders.functionScoreQuery(boolQuery,new
                FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD",true),
                                ScoreFunctionBuilders.weightFactorFunction(10)
                        )
        });

        // 放入source
        request.source().query(boolQuery);
    }

    private PageResult handleResponse(SearchResponse response) {
        //4.解析响应
        SearchHits searchHits = response.getHits();
        //4.1 获取总记录数
        long total = searchHits.getTotalHits().value;
        //4.2 获取文档数组
        ArrayList<HotelDoc> hotels = new ArrayList<>();
        SearchHit[] hits = searchHits.getHits();
        for (SearchHit hit : hits) {
            //获取文档source
            String json = hit.getSourceAsString();
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
            //处理高亮
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if(CollectionUtil.isNotEmpty(highlightFields)){
                HighlightField highlightField = highlightFields.get("name");
                if(highlightField != null){
                    String name = highlightField.getFragments()[0].string();
                    hotelDoc.setName(name);
                }
            }
            //处理近距离显示
            Object[] sortValues = hit.getSortValues();
            if(ArrayUtil.isNotEmpty(sortValues)){
                Object sortValue = sortValues[0];
                hotelDoc.setDistance(sortValue);
            }
            //放入集合
            hotels.add(hotelDoc);
        }
        return new PageResult(total,hotels);
    }
}
